package com.example.ucsur;

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;



public class SearchLocationActivity extends Activity implements
	GooglePlayServicesClient.ConnectionCallbacks,
	GooglePlayServicesClient.OnConnectionFailedListener
	{
	    // Global constants
	    /*
	     * Define a request code to send to Google Play services
	     * This code is returned in Activity.onActivityResult
	     */
    ConnectionResult connectionResult = null;
	JSONObject jsonObjectFromArray;
	JSONArray jsonArrayFromHttp = new JSONArray();
	JSONObject jsonObjectFromHttp;
    LocationClient mLocationClient;
    LocationListener sup;
    LocationRequest sup1;
    GoogleMap map;
    LatLng latLonFromHttp;
    int timer = 0;
    LatLng position;
    	String result;
    	String latitude;
    	Location mCurrentLocation;
    	String lon;
	    private final static int
	            CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
	    
	    
	    
		public class DoPOSTS extends AsyncTask<String, Void, Boolean>{


			
			//Set up any POST variables we need.
			Context mContext = null;
			String strLatToSearch = "";
			String strLonToSearch = "";
			String choice1 = new String("Address");
			String choice2 = new String("ZipCode");
			int fieldCode;
			Button buttonsFromResults[] = new Button[50];
			Exception exception = null;
			
			Exception exception1;
			int arraylength;
			
			//Default constructors.
			DoPOSTS(Context context, String latToSearch, String lonToSearch){
				mContext = context;
				strLatToSearch = latToSearch;
				strLonToSearch = lonToSearch;
			}
			

			@Override
			protected Boolean doInBackground(String... arg0) {

				try{

					//Setup the parameters
					ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("FirstLatToSearch", strLatToSearch));
					nameValuePairs.add(new BasicNameValuePair("FirstLonToSearch", strLonToSearch));
					nameValuePairs.add(new BasicNameValuePair("CurLat", latitude));
					nameValuePairs.add(new BasicNameValuePair("CurLon", lon));
					//Add more parameters as necessary

					//Create the HTTP request
					HttpParams httpParameters = new BasicHttpParams();

					//Setup timeouts
					HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
					HttpConnectionParams.setSoTimeout(httpParameters, 15000);			

					HttpClient httpclient = new DefaultHttpClient(httpParameters);
					HttpPost httppost = new HttpPost("http://bhunsaker.pairserver.com/address_search.php");
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));        
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();

					result = EntityUtils.toString(entity);
					// Create a JSON array from the request response
					try
					{
						jsonArrayFromHttp = new JSONArray(result);
						arraylength = jsonArrayFromHttp.length();
					}
					//Catch exception that we only get one result. Use a JSON array instead.
					catch (Exception e)
					{
						jsonObjectFromHttp = new JSONObject(result);
							Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();

					}
					
					
				}catch (Exception e){
					Log.e("ClientServerDemo", "Error:", e);
					exception = e;
				}

				return true;
			}

			//On valid execute, run method to create buttons for each result.
			@Override
			protected void onPostExecute(Boolean valid){
				//Update the UI
				final int[] buttonHashCodes = new int[50];
				Marker location = map.addMarker(new MarkerOptions()
				.title("Current Location")
				.position(position));
		        LatLng position1 = new LatLng(40, 80);
		        String address = new String("");
		        for (int j=0;j<arraylength;j++)
		        {
			        JSONObject object1 = new JSONObject();
			        JSONObject object2;
			        try {
						object1 = jsonArrayFromHttp.getJSONObject(j);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        try {
						position1 = new LatLng(object1.getDouble("y"), object1.getDouble("x"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        try {
						address = object1.getString("PropertyHouseNum") + " " + object1.getString("PropertyAddress");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					final String data = object1.toString();
		        Marker marker = map.addMarker(new MarkerOptions()
		        .title(address)
		        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
		        .position(position1));
		        buttonHashCodes[j] = marker.hashCode();
		        }
		        map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
		        	@Override
		        	public void onInfoWindowClick(Marker marker) {
		        		Intent intent = new Intent(getBaseContext(), ThumbActivity.class);
						//intent.putExtra("address", address);
		        		String actualData = new String("");
		        		for (int i=0;i<arraylength;i++)
		        		{
		        			if (marker.hashCode() == buttonHashCodes[i])
		        			{
		        				try {
									actualData = jsonArrayFromHttp.getJSONObject(i).toString();
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
		        			}
		        		}
						intent.putExtra("dataFromActivity", actualData);
						startActivity(intent);
		        		}
		        	});
		        }
			}
	    
	    
	    
		
	    	   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
			@Override
	    protected void onCreate(Bundle savedInstanceState) {
	        /*
	         * Create a new location client, using the enclosing class to
	         * handle callbacks.
	         */
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_locationmap);
	        mLocationClient = new LocationClient(this, this, this);
	    }
	    	   
	    	   
	    	   // Define a DialogFragment that displays the error dialog
	    @SuppressLint("NewApi")
		public static class ErrorDialogFragment extends DialogFragment {
	        // Global field to contain the error dialog
	        private Dialog mDialog;
	        // Default constructor. Sets the dialog field to null
	        @SuppressLint("NewApi")
			public ErrorDialogFragment() {
	            super();
	            mDialog = null;
	        }
	        // Set the dialog to display
	        public void setDialog(Dialog dialog) {
	            mDialog = dialog;
	        }
	        // Return a Dialog to the DialogFragment.
	        @Override
	        public Dialog onCreateDialog(Bundle savedInstanceState) {
	            return mDialog;
	        }
	    }
	    /*
	     * Handle results returned to the FragmentActivity
	     * by Google Play services
	     */
	    @Override
	    protected void onActivityResult(
	            int requestCode, int resultCode, Intent data) {
	        // Decide what to do based on the original request code
	        switch (requestCode) {
	            case CONNECTION_FAILURE_RESOLUTION_REQUEST :
	            /*
	             * If the result code is Activity.RESULT_OK, try
	             * to connect again
	             */
	                switch (resultCode) {
	                    case Activity.RESULT_OK :
	                    /*
	                     * Try the request again
	                     */
	                    break;
	                }
	        }
	     }
	    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
		private boolean servicesConnected() {
	        // Check that Google Play services is available
	        int resultCode =
	                GooglePlayServicesUtil.
	                        isGooglePlayServicesAvailable(this);
	        // If Google Play services is available
	        if (ConnectionResult.SUCCESS == resultCode) {
	            // In debug mode, log the status
	            Log.d("Location Updates",
	                    "Google Play services is available.");
	            // Continue
	            return true;
	        // Google Play services was not available for some reason
	        } else {
				// Get the error code
	            int errorCode = connectionResult .getErrorCode();
	            // Get the error dialog from Google Play services
	            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
	                    errorCode,
	                    this,
	                    CONNECTION_FAILURE_RESOLUTION_REQUEST);

	            // If Google Play services can provide an error dialog
	            if (errorDialog != null) {
	                // Create a new DialogFragment for the error dialog
	                ErrorDialogFragment errorFragment =
	                        new ErrorDialogFragment();
	                // Set the dialog in the DialogFragment
	                errorFragment.setDialog(errorDialog);
	                // Show the error dialog in the DialogFragment
	                errorFragment.show(getFragmentManager(),
	                        "Location Updates");
	            }
	        }
			return false;
	    }
	    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
	    public void onConnected(Bundle dataBundle) {
	        // Display the connection status
	        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
	        LocationManager locationManagerNetwork = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
	        String locationProviderNetwork = LocationManager.NETWORK_PROVIDER;
	        //LocationManager locationManagerGPS = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
	        //String locationProviderGPS = LocationManager.GPS_PROVIDER;
	        android.location.LocationListener locationListener;
	        
	        locationListener = new LocationListener() {
	            public void onLocationChanged(Location location) {
	                // Called when a new location is found by the network location provider.
	                //makeUseOfNewLocation(location);
	            	//latitude = new String("" + location.getLatitude());
	            	//lon = new String("" + location.getLongitude());
	            	mCurrentLocation = location;
	              }

	              public void onStatusChanged(String provider, int status, Bundle extras) {}

	              public void onProviderEnabled(String provider) {}

	              public void onProviderDisabled(String provider) {}
	            };
	            mCurrentLocation = locationManagerNetwork.getLastKnownLocation(locationProviderNetwork);
	        //locationManagerGPS.requestLocationUpdates(locationProviderGPS, (long)5000.0, (float)50.0, locationListener);   
		    locationManagerNetwork.requestLocationUpdates(locationProviderNetwork, (long)1.0, (float)50.0, locationListener);
		    //Location mCurrentLocation = locationManagerNetwork.getLastKnownLocation(locationProviderNetwork);
		    	//locationManagerNetwork.requestLocationUpdates(locationProviderNetwork, (long)5000.0, (float)50.0, locationListener);
	        map = ((MapFragment) getFragmentManager()
	                .findFragmentById(R.id.map2)).getMap();
	        //while (mCurrentLocation == null);
	        position = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
	        map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 18));
	        latitude = new String("" + mCurrentLocation.getLatitude());
	        lon = new String("" + mCurrentLocation.getLongitude());
	        if (timer == 0)
	        {
	        	DoPOSTS doPOST = new DoPOSTS(SearchLocationActivity.this, latitude, lon);
	        	doPOST.execute("");
	        	timer++;
	        }
	    }

	    /*
	     * Called by Location Services if the connection to the
	     * location client drops because of an error.
	     */
	    @Override
	    public void onDisconnected() {
	        // Display the connection status
	        Toast.makeText(this, "Disconnected. Please re-connect.",
	                Toast.LENGTH_SHORT).show();
	    }
	    /*
	     * Called by Location Services if the attempt to
	     * Location Services fails.
	     */
	    @SuppressWarnings("deprecation")
		@Override
	    public void onConnectionFailed(ConnectionResult connectionResult) {
	        /*
	         * Google Play services can resolve some errors it detects.
	         * If the error has a resolution, try sending an Intent to
	         * start a Google Play services activity that can resolve
	         * error.
	         */
	        if (connectionResult.hasResolution()) {
	            try {
	                // Start an Activity that tries to resolve the error
	                connectionResult.startResolutionForResult(
	                        this,
	                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
	                /*
	                 * Thrown if Google Play services canceled the original
	                 * PendingIntent
	                 */
	            } catch (IntentSender.SendIntentException e) {
	                // Log the error
	                e.printStackTrace();
	            }
	        } else {
	            /*
	             * If no resolution is available, display a dialog to the
	             * user with the error.
	             */
	            showDialog(connectionResult.getErrorCode());
	        }
	    }
	    /*
	     * Called when the Activity becomes visible.
	     */
	    @Override
	    protected void onStart() {
 	        super.onStart();
	        // Connect the client.
	        mLocationClient.connect();
	    }
	    /*
	     * Called when the Activity is no longer visible.
	     */
	    @Override
	    protected void onStop() {
	        // Disconnecting the client invalidates it.
	        mLocationClient.disconnect();
	        super.onStop();
	    }

	}
